# -*- coding:utf8 -*-
#encoding = utf-8
__author__ = 'man' 

#		_________________________________________________________________________________
#
#						漫鸽网络技术服务(mangenotwork)拥有所有权
#						@www.hbsj.xyz   
#						@www.mangenotwork.com
#			严重声明：原始代码属于"漫鸽网络技术服务(mangenotwork)"的知识产权，拥有法律的保护，
#		请勿抄袭、转载、删除、私用、篡改、破坏...
#
#       
#		简介 ：  collect.py 收藏API,详情API,批发API
#		作者 ： 李漫(man)
#		创建时间:  20190620
#		
#		_________________________________________________________________________________

from flask import Flask,request,g,render_template,redirect,url_for,abort,session,jsonify,current_app
from flask import Blueprint , render_template
from flask import make_response,Response 
import sys,os
import json
import time
import datetime
import redis
from cryptography.fernet import Fernet
#md5
import hashlib
import db.mandb
'''
man_db = db.mandb.DB()
print(man_db.db_connect())
'''
collect = Blueprint('collect',__name__)
#函数不能命名 test



'''
					#类型： DB交互
					#执行查询  查询结果
'''
def ManDB(func=None, param=None):
	def deco(func):
		def wrapper(*args,**kwargs):
			man_db = db.mandb.DB()
			return func(man_db,*args,**kwargs)			
		wrapper.__name__ = func.__name__
		return wrapper
	return deco if not func else deco(func)


'''
					#类型： 接口
					#函数不能命名 test
					#使用者 : wap
'''
@collect.route('/collect_test', methods=['POST','GET'])
def collect_test():
	return "This is a Blueprint : collect Test."



'''
					#类型： 函数，方法
					#获取IP
'''
def get_user_ip():
    print(request.remote_addr)
    return request.remote_addr


#用户身份识别
def userACC():
    userToken=request.cookies.get('user_token')
    print("[Get Cookies] = "+str(userToken))
    username=request.cookies.get('user_name')
    print("[Get username] = "+str(username))

    keys = session.get(userToken)
    print("[Get keys] = "+str(keys))
    if userToken != None and keys == username:
        return True
    else:
        return False


'''
					#类型： 接口
					#收藏接口
					#采用后台读取再写到收藏表的方式，启到保护数据
					#如果前端传，安全风险更高
					#使用者 : wap
'''
@collect.route('/collectCod', methods=['POST','GET'])
def collect_cod():
	resp = make_response()
	resp.status_code = 200
	if userACC() == True:
		if request.method == "POST":
			datax = request.form.to_dict()
		codlinks = datax["links"]
		codlinks = str(codlinks)
		print(codlinks)
		pingtai_type_val = codlinks.split("_")[0]
		codid_val = codlinks.split("_")[1]
		print(pingtai_type_val)
		print(codid_val)
		hbsj_user_acc = request.cookies.get('user_acc')
		#hbsj_user_id = session.get(hbsj_user_acc)

		useruuid=request.cookies.get('user_uuid')
		print("userUUID = "+ str(useruuid))

		if useruuid != None:
			collect_select(pingtai_type_val,codid_val,useruuid,codlinks)
			returndata = 1
		else:
			returndata = -1
	else:
		returndata = 0
		#resp.response = render_template('login.html',my=1)
	resp.response = json.dumps(returndata).encode('utf-8').decode("unicode-escape")
	return resp



'''
					#类型： DB交互
					#获取收藏的商品对应的信息
'''
@ManDB
def collect_select(man_db,pingtai_type,ids,hbsj_user_acc,cod_id):
	if pingtai_type == "tbtm":
		sql = "SELECT  title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name,cod_fenlei\
					from tb_tm_pachong_data_1\
					where pachong_data_id = "+ids+";"
		print("Tb Tm")

	elif pingtai_type == "sn":
		sql = "SELECT  title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name,cod_fenlei\
					from sn_pachong_data_1\
					where pachong_data_id = "+ids+";"
		print("SN")

	elif pingtai_type == "jd":
		sql = "SELECT title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name,cod_fenlei\
					from jd_pachong_data_1\
					where pachong_data_id = "+ids+";"
		print("JD")
	print(sql)
	return_datas = man_db.execute_seles(sql)[0]
	print(return_datas)
	print(hbsj_user_acc)
	ticks = time.time()
	sclist_cod = [hbsj_user_acc,str(ticks),str(cod_id)]
	for coddata in return_datas:
		print(coddata)
		sclist_cod.append(str(coddata))
	print(sclist_cod)
	sc_input_db(sclist_cod)

"""
CREATE TABLE sc_info_1(
	scinfo_id INT UNSIGNED AUTO_INCREMENT,/* 收藏ID   主(不可重复) */

	user_uuid char(50) NOT NULL,/* 用户UUID */
	sc_time char(35) NOT NULL,/* 收藏时间 */
	cod_id char(30) NOT NULL,
	cod_fenlei char(30) NOT NULL,/* 商品分类 */
	cod_name char(100) NOT NULL,/* 商品名称 */
	cod_link VARCHAR(5000) NOT NULL,/* 商品链接 */
	pingtai char(15) NOT NULL,
	cod_price_1 char(50) NOT NULL,/* 实际价格 */
	cod_price_2 char(50) NOT NULL,/* 活动价格 */
	title_img_link VARCHAR(2000) NOT NULL,/* 图片 */
	cod_sales char(30) NOT NULL,/* 商品销量/评价 */
	cod_shop_name char(50) NOT NULL,/* 店家名称 */
	
	PRIMARY KEY (scinfo_id)

"""


'''
					#类型： DB交互
					#收藏商品
'''
@ManDB
def sc_input_db(man_db,infodata):
	sql = "INSERT INTO sc_info_1 ( user_uuid, sc_time,cod_id,title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name,cod_fenlei) \
			VALUES ( '"+infodata[0]+"', '"+infodata[1]+"', '"+infodata[2]+"', '"+infodata[3]+"', '"+infodata[4]+"', '"+infodata[5]+"'\
			, '"+infodata[6]+"', '"+infodata[7]+"', '"+infodata[8]+"', '"+infodata[9]+"', '"+infodata[10]+"','"+infodata[11]+"');"
	man_db.execute(sql)



'''
					#类型： DB交互
					#获取我的收藏
'''
@ManDB
def get_my_sc(man_db,useruuid):
	sql = "SELECT  title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name,cod_id\
					from sc_info_1\
					where user_uuid = '"+useruuid+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas


'''
					#类型： 函数方法
					#返回前端的收藏数据整理
'''
def sc_codlist(datasinfo):
    add_list = []
    title_img_link = datasinfo[0]
    cod_name = datasinfo[1]
    if len(cod_name)>12:
        cod_name = cod_name[0:12]+"..."
    cod_link = datasinfo[2]
    cod_price_1 = datasinfo[3]
    cod_price_2 = datasinfo[4]
    cod_sales = datasinfo[5]
    pingtai = datasinfo[6]
    cod_shop_name = datasinfo[7]
    cod_id = datasinfo[8]
    if len(cod_shop_name)>10:
        cod_shop_name = cod_shop_name[0:10]+"..."
    if cod_price_1 == "":
        cod_price_1 = "没有特价"
    cod_name = cod_name.strip()
    print(cod_id)
    add_list=[title_img_link,cod_name,cod_link,
              str(cod_price_2),cod_sales,pingtai,cod_shop_name,cod_id]
    print(add_list)
    return add_list



"""
								[ 查询sql ]


37s
select title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from (
(SELECT  title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from tb_tm_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html')
UNION
(SELECT title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from sn_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html'
)
UNION
(SELECT title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from jd_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html'
)
)as t



7s
SELECT  title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from tb_tm_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html';


1s
SELECT title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from sn_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html';


14s
SELECT title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from jd_pachong_data_1
where cod_link = 'http://item.jd.com/32962088952.html';





SELECT  pachong_data_id,title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from tb_tm_pachong_data_1
where pachong_data_id = ;



SELECT  pachong_data_id,title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from sn_pachong_data_1
where pachong_data_id = ;



SELECT  pachong_data_id,title_img_link,cod_name,cod_link,cod_price_1,cod_price_2,cod_sales,pingtai,cod_shop_name
from jd_pachong_data_1
where pachong_data_id = 6644;


"""


#查询 京东 商品详情数据
@ManDB
def get_jdcod_xq(man_db,codid):
	sql = "SELECT cod_name,cod_link,title_img_link,cod_price_1,cod_price_2,cod_sales,cod_fenlei,pingtai,cod_shop_name,shop_fen_s_lve,\
					shop_fen_w_lve,shop_fen_f_lve,shopLevel_info,showLicence_info,collection_time\
					from jd_pachong_data_1\
					where pachong_data_id = '"+codid+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas



#查询 淘宝天猫 商品详情数据
@ManDB
def get_tbtmcod_xq(man_db,codid):
	sql = "SELECT cod_name,cod_link,title_img_link,cod_price_1,(cod_price_2/100),cod_sales,cod_fenlei,pingtai,cod_shop_name,cod_shop_location,\
					collection_time\
					from tb_tm_pachong_data_1\
					where pachong_data_id = '"+codid+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas


#查询 苏宁 商品详情数据
@ManDB
def get_sncod_xq(man_db,codid):
	sql = "SELECT cod_name,cod_link,title_img_link,cod_price_1,cod_price_2,cod_sales,cod_fenlei,pingtai,cod_shop_name,cod_shop_home,\
					cod_shop_grade_s,cod_shop_grade_w,cod_shop_grade_f,cod_shop_location,collection_time\
					from sn_pachong_data_1\
					where pachong_data_id = '"+codid+"';"
	return_datas = man_db.execute_seles(sql)
	return return_datas


#商品详情 接口
@collect.route('/codinfo', methods=['POST','GET'])
def cod_info():
	if request.method == "GET":
		codid = request.args.get('xqdatas')
	print(codid)

	codtype = codid.split("_")[0]
	thisid = codid.split("_")[-1]
	print(codtype)
	print(thisid)

	if codtype == "jd":
		#在京东查找数据并显示
		codinfo_data = get_jdcod_xq(thisid)
		print(codinfo_data)
		return render_template('codinfo.html',jdshow=1,infodatas = codinfo_data[0])
	elif codtype == "tbtm":
		#在淘宝天猫查找数据并显示
		codinfo_data = get_tbtmcod_xq(thisid)
		print(codinfo_data)
		return render_template('codinfo.html',tbtmshow=1,infodatas = codinfo_data[0])
	elif codtype == "sn":
		#在苏宁查询数据并显示
		codinfo_data = get_sncod_xq(thisid)
		print(codinfo_data)
		return render_template('codinfo.html',snshow=1,infodatas = codinfo_data[0])





#获取批发信息db交互
@ManDB
def get_pifaData_1(man_db,get_type=None,pgnumber=0):
	if get_type == None:
		sql = "SELECT cod_name,cod_link,cod_img,cod_price,fenlei,shop_type,shop_name,shop_site\
						from 1688_data_1 LIMIT "+str(int(pgnumber)*30)+",30;"
	elif get_type == "jxpf":
		sql = "SELECT cod_name,cod_link,cod_img,cod_price,fenlei,shop_type,shop_name,shop_site\
						from 1688_data_1 \
						where shop_type = '经销批发'\
						LIMIT "+str(int(pgnumber)*30)+",30;"
	elif get_type == "scjg":
		sql = "SELECT cod_name,cod_link,cod_img,cod_price,fenlei,shop_type,shop_name,shop_site\
						from 1688_data_1 \
						where shop_type = '生产加工'\
						LIMIT "+str(int(pgnumber)*30)+",30;"
	elif get_type == "zsdl":
		sql = "SELECT cod_name,cod_link,cod_img,cod_price,fenlei,shop_type,shop_name,shop_site\
						from 1688_data_1 \
						where shop_type = '招商代理'\
						LIMIT "+str(int(pgnumber)*30)+",30;"
	return_datas = man_db.execute_seles(sql)
	return return_datas




#批发API  批发接口
@collect.route('/pifainfo', methods=['POST','GET'])
def pifa_info():
	if request.method == "GET":
		gettype = request.args.get('gettype')

	print(gettype)
	returndatas = get_pifaData_1(gettype)
	

	alllist = []
	for datas in returndatas:
		if len(datas[0]) > 28:
			name = datas[0][0:26]+"..."
		else:
			name = datas[0]
		lists = [name,datas[1],datas[2],datas[3],datas[4],datas[5],datas[6],datas[7]]
		alllist.append(lists)
		lists = []
	print(alllist)

	if gettype == None:
		return render_template('pifapg.html',infolist = alllist, all=1 )
	elif gettype == "jxpf":
		return render_template('pifapg.html',infolist = alllist, jxpf=1 )
	elif gettype == "scjg":
		return render_template('pifapg.html',infolist = alllist, scjg=1 )
	elif gettype == "zsdl":
		return render_template('pifapg.html',infolist = alllist, zsdl=1 )




#批发API  批发页面下拉请求数据接口
@collect.route('/getpifaDatas', methods=['POST','GET'])
def getpifa_datas():
    if request.method == "GET":
        pgnum = request.args.get('numb')
        gettype = request.args.get('gettype')
    print(pgnum)

    returndatas = get_pifaData_1(gettype,pgnum)

    alllist = []
    for datas in returndatas:
        if len(datas[0]) > 28:
            name = datas[0][0:26]+"..."
        else:
            name = datas[0]
        lists = [name,datas[1],datas[2],datas[3],datas[4],datas[5],datas[6],datas[7]]
        alllist.append(lists)
        lists = []
    print(alllist)


    resp = make_response()
    resp.status_code = 200
    resp.response = json.dumps(alllist).encode('utf-8').decode("unicode-escape")
    return resp





